package com.sofwin;

import com.sofwin.system.pojo.SysUser;
import com.sofwin.system.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @packageName: com.sofwin
 * @user: andyliu
 * @date: 2021/7/20 16:29
 * @email 115176513@qq.com
 * @description: TODO
 */

public class UserRealm extends SimpleAccountRealm {
    private UserService userService;
    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken t = (UsernamePasswordToken)token;
        String userName = t.getUsername();// 唯一的登陆名
        String pwd = new String(t.getPassword());
        SysUser user = new SysUser();
        user.setLoginAccount(userName);
        user.setLoginPwd(pwd);
        // 通过token获取到主体中的唯一标示和密码
        AjaxResult ajaxResult = userService.checkLogin(user);
        if(ajaxResult.getCode()==501){
            throw new UnknownAccountException();
        }
        if(ajaxResult.getCode()==502){
            throw new AuthenticationException();
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userName,pwd,getName());
        return info;
    }
    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return super.doGetAuthorizationInfo(principals);
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
